package com.example.blogdemo1.common.interceptor;

import com.example.blogdemo1.common.utils.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/*
 * @author zzr
 * @date: 2025/10/06  14:22
 * @description:
 */

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 从 header 中获取 token
        String jwtToken = request.getHeader("user_token");
        log.info("从 header 中获取 token：{}",jwtToken);
        // 验证 token
        Claims claims = JWTUtils.parseToken(jwtToken);
        if (null != claims) {
            log.info ("令牌验证成功，放行");
            return true;
        }

        response.setStatus(401);
        log.info("令牌验证失败");
        return false;

    }
}
